import React, { FC, ReactElement, useState, useRef } from 'react';
import style from './index.less';
import { Form, Input, Button, Image, message } from 'antd';
import { history, Link, connect } from 'umi';
import { UserOutlined, UnlockOutlined } from '@ant-design/icons';
import {
  loginMyIdTo,
  getListFirstLevelMenuForUser,
  getListOthersMenuForUserUrl,
} from '@/services';
import { encrypt } from '@/untils/pswEncryption';

interface route {
  menuId: string;
  menuName: string;
  menuUrl: string;
  parentId: string;
  items: route[];
}
const Login: FC = (IProps: any): ReactElement => {
  const { dispatch } = IProps;
  const imgHeight = window.outerHeight - 72;
  const imgWidth = (window.outerWidth - 8) * 0.7;
  const demoSrc = require('../../assets/img/登录.png');
  let formRef = useRef(null);
  const getMenu = async () => {
    let resRoutes: route[] = [];
    let proMList: Promise<route[]>[] = [];
    await getListFirstLevelMenuForUser().then((res) => {
      if (res.code === 200) {
        res.data.forEach((item: route) => {
          resRoutes.push({ ...item, items: [] });
          proMList.push(
            new Promise((resolve, reject) => {
              getListOthersMenuForUserUrl({ parentId: item.menuId }).then(
                (res) => {
                  if (res.code === 200) {
                    let route: route[] = [];
                    res.data.forEach((items: route) => {
                      route.push({ ...items, items: [] });
                    });
                    resolve(route);
                  }
                },
              );
            }),
          );
        });
      }
    });
    await Promise.all(proMList).then((res) => {
      res.forEach((proItem, proIndex) => {
        resRoutes[proIndex].items = proItem;
      });
    });
    resRoutes.push({
      menuId: '1002',
      menuName: '组织架构',
      menuUrl: '/org',
      parentId: '0',
      items: [
        {
          menuId: '1003',
          menuName: '组织架构管理',
          menuUrl: '/organization',
          parentId: '0',
          items: [],
        },
        {
          menuId: '1004',
          menuName: '内嵌编辑表格',
          menuUrl: '/innerEditTable',
          parentId: '0',
          items: [],
        },
      ],
    });

    console.log(resRoutes, 11);

    localStorage.setItem('routes', JSON.stringify(resRoutes));
    setTimeout(() => {
      history.push('/');
    }, 0);
  };
  const onFinish = (values: any) => {
    const { userAccount, userPwd } = values;

    loginMyIdTo({
      userAccount,
      userPwd: encrypt(userPwd),
    }).then((res) => {
      if (res.code === 200) {
        localStorage.setItem('user', JSON.stringify(res.data));

        message.success('登录成功！');
        console.log('登录成功', res);

        getMenu();
        //
        dispatch({
          type: 'userData/setUser',
          payload: res.data,
        });

        history.push('/');
      } else {
        message.error(res.message);
      }
    });
  };
  const { loginContentBox, loginBoxTitle, loginFormBox, submitBtn } = style;
  return (
    <div>
      <Image
        src={demoSrc}
        height={imgHeight}
        width={imgWidth}
        preview={false}
      ></Image>
      <div className={loginContentBox}>
        <div className={loginBoxTitle}>秦学后台管理</div>
        <Form
          ref={formRef}
          name="control-ref"
          onFinish={onFinish}
          className={loginFormBox}
        >
          <Form.Item
            name="userAccount"
            rules={[{ required: true, message: '请输入您的用户名!' }]}
          >
            <Input
              size="large"
              placeholder="请输入用户名"
              prefix={<UserOutlined />}
            />
          </Form.Item>
          <Form.Item
            name="userPwd"
            rules={[{ required: true, message: '请输入您的密码!' }]}
          >
            <Input.Password
              size="large"
              placeholder="请输入密码"
              prefix={<UnlockOutlined />}
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className={submitBtn}
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
        <Link to="">使用手机小程序提示的账号密码登录</Link>
      </div>
    </div>
  );
};
export default connect(({ userData }: any) => ({ userData }))(Login);
